package org.scboy.dbms.init;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.dbms.annotation.ValidType;
import org.scboy.dbms.dao.BaseValidClassDao;
import org.scboy.dbms.entity.ParamConfig;
import org.scboy.dbms.valid.Valid;
import org.scboy.utils.entitys.coobi.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;

import com.google.gson.Gson;

import cn.hutool.core.lang.ClassScanner;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * 验证初始化
 */
@Configuration
public class VlidTypeInit  implements ApplicationListener<ApplicationReadyEvent>{
	
	Log log=LogFactory.get();
	
	@Autowired
	EntityFactory factory;
	
	@Override
	public void onApplicationEvent(ApplicationReadyEvent event) {
		
		BaseValidClassDao dao=factory.getDao(BaseValidClassDao.class);
		
		Set<Class<?>> scanner=ClassScanner.scanPackage("org.scboy.dbms.valid");
		for (Class<?> clazz : scanner) {
			if(Valid.class.isAssignableFrom(clazz)&&!clazz.isInterface()&&clazz.isAnnotationPresent(ValidType.class)){
				String validClass=clazz.getName();
				//验证名称
				String validName=clazz.getAnnotation(ValidType.class).value();
				log.info(StrUtil.format("检查到验证类[{}({})]", validName,validClass));
				//查询jobClass数据库配置
				Model vlidClassModel=dao.get(Model.create().add("className", validClass));
				if(vlidClassModel==null){
					vlidClassModel=Model.create();
					vlidClassModel.add("className", validClass);
					try {
						Valid valid=(Valid)clazz.getDeclaredConstructor().newInstance();
						List<ParamConfig> params=valid.config();
						if(params==null)params=new ArrayList<ParamConfig>();
						vlidClassModel.add("configParams", new Gson().toJson(params));
					} catch (Exception e) {
						log.error(e);
					}
					vlidClassModel.add("validName", validName);
					dao.insert(vlidClassModel);
				}else{
					try {
						Valid valid=(Valid)clazz.getDeclaredConstructor().newInstance();
						List<ParamConfig> params=valid.config();
						if(params==null)params=new ArrayList<ParamConfig>();
						vlidClassModel.add("configParams", new Gson().toJson(params));
					} catch (Exception e) {
						log.error(e);
					}
					vlidClassModel.add("validName", validName);
					dao.update(vlidClassModel,Model.create().add("className", validClass));
				}
			}
		}
	}
}
